"""Update to v2.0

Revision ID: 6160f5a009be
Revises: 
Create Date: 2024-01-10 15:31:19.289101

"""
from typing import Sequence, Union
from datetime import datetime as dt

from alembic import op
import sqlalchemy as sa

from sqlalchemy.sql import table, column
from sqlalchemy.engine.reflection import Inspector

from models import Account


# revision identifiers, used by Alembic.
revision: str = '6160f5a009be'
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def is_table_exist(table_name):
    inspector = Inspector.from_engine(op.get_bind())
    return table_name in inspector.get_table_names()

def is_column_exist(table_name, column_name):
    inspector = Inspector.from_engine(op.get_bind())
    if not is_table_exist(table_name):
        return False
    columns = [col['name'] for col in inspector.get_columns(table_name)]
    return column_name in columns


def upgrade() -> None:

    meta = sa.MetaData()
    meta.reflect(bind=op.get_bind(), only=('account_info',))

    old_table = meta.tables['account_info']

    # 重命名旧表为新表名
    old_table_name = f'_account_info_old_{dt.now().strftime("%Y_%m_%d_%s")}'
    op.rename_table('account_info', old_table_name)

    # 创建新表的定义，包括列的新顺序
    new_table = Account.__table__

    # 创建新表
    new_table.create(bind=op.get_bind())

    # 将原表数据复制到新表
    op.execute(f'INSERT INTO account_info (id, email, password, is_active, web_access_token, web_session_token, pandora_share_token, created_at) SELECT id, email, password, is_active, access_token, session_token, share_token, created_at FROM {old_table_name}')

    # 删除原表
    # old_table.drop()

    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###

    pass

    # ### end Alembic commands ###
